package com.icongyou.enterprise.talent_marking.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.icongyou.enterprise.data_aggregation.entity.*;
import com.icongyou.enterprise.data_aggregation.mapper.DataAggregationMapper;
import com.icongyou.enterprise.talent_marking.entity.PerformanceChanges;
import com.icongyou.enterprise.talent_marking.entity.StudentPerformanceSnapshots;
import com.icongyou.enterprise.talent_marking.mapper.PerformanceChangeMapper;
import com.icongyou.enterprise.talent_marking.mapper.StudentPerformanceTrackingServiceMapper;
import com.icongyou.enterprise.talent_marking.service.StudentPerformanceTrackingService;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class StudentPerformanceTrackingServiceImpl implements StudentPerformanceTrackingService {

    @Resource
    private PerformanceChangeMapper changesMapper;
    @Resource
    private StudentPerformanceTrackingServiceMapper trackingServiceMapper;
    @Resource
    private DataAggregationMapper dataAggregationMapper;
    @Autowired
    private StudentPerformanceTrackingServiceMapper studentPerformanceTrackingServiceMapper;

    /**
     * 简化的每周跟踪任务 - 只跟踪5个核心方面
     */
    @Scheduled(cron = "0 0 2 * * MON")
    //@Scheduled(initialDelay = 10000, fixedRate = 300000)//测试用 每5分钟执行一次
    @Transactional
    public void simplifiedWeeklyTracking() {

        List<String> trackedStudentIds = getTrackedStudentIds();

        for (String studentId : trackedStudentIds) {
            try {
                generateSimplifiedSnapshot(studentId);
                detectSimplifiedChanges(studentId);
            } catch (Exception e) {
            }
        }

    }

    /**
     * 生成简化快照 - 只存跟踪所需数据
     */
    private void generateSimplifiedSnapshot(String studentId) {
        LocalDate snapshotDate = LocalDate.now();
        List<CourseProgressEntity> courses = dataAggregationMapper.selectCourseProgressByStudentId(studentId);

        for (CourseProgressEntity course : courses) {
            String courseId = course.getCourseId();

            // 检查是否已存在本周快照
            if (trackingServiceMapper.existsSnapshot(studentId, courseId, snapshotDate)) {
                continue;
            }

            StudentPerformanceSnapshots snapshot = new StudentPerformanceSnapshots();
            snapshot.setId(UUID.randomUUID().toString());
            snapshot.setStudentId(studentId);
            snapshot.setCourseId(courseId);
            snapshot.setCourseName(dataAggregationMapper.selectCourseNameById(courseId));
            snapshot.setSnapshotDate(snapshotDate);

            // 只设置跟踪所需的5个方面数据
            snapshot.setCourseTotalScore(course.getTotalScore());
            snapshot.setCourseRanking(course.getRanking());
            snapshot.setCompletedTasks(course.getCompletedTasks());
            snapshot.setRecentContributions(getRecentContributions(studentId, courseId));
            snapshot.setActiveAssignments(getActiveAssignments(studentId, courseId));

            trackingServiceMapper.insert(snapshot);
        }
    }

    /**
     * 简化的变化检测 - 只检测5个方面
     */
    private void detectSimplifiedChanges(String studentId) {
        LocalDate currentDate = LocalDate.now();
        LocalDate lastWeek = currentDate.minusWeeks(1);

        List<CourseProgressEntity> currentCourses = dataAggregationMapper.selectCourseProgressByStudentId(studentId);

        for (CourseProgressEntity currentCourse : currentCourses) {
            String courseId = currentCourse.getCourseId();

            StudentPerformanceSnapshots lastSnapshot = trackingServiceMapper
                    .selectByStudentAndCourseAndDate(studentId, courseId, lastWeek);

            if (lastSnapshot == null) {
                continue;
            }

            // 1. 检测课程分数变化
            detectScoreChange(studentId, currentCourse, lastSnapshot);

            // 2. 检测排名变化
            detectRankingChange(studentId, currentCourse, lastSnapshot);

            // 3. 检测进度变化
            detectProgressChange(studentId, currentCourse, lastSnapshot);

            // 4. 检测新任务变化
            detectNewAssignments(studentId, courseId, lastWeek);

            // 5. 检测贡献度变化
            detectContributionChanges(studentId, courseId, lastSnapshot, lastWeek);
        }
    }

    /**
     * 1. 检测课程分数变化
     */
    private void detectScoreChange(String studentId, CourseProgressEntity current, StudentPerformanceSnapshots last) {
        if (current.getTotalScore() != null && last.getCourseTotalScore() != null) {
            BigDecimal currentScore = current.getTotalScore();
            BigDecimal lastScore = last.getCourseTotalScore();

            if (currentScore.compareTo(lastScore) != 0) {
                PerformanceChanges change = new PerformanceChanges();
                change.setId(UUID.randomUUID().toString());
                change.setStudentId(studentId);
                change.setCourseId(current.getCourseId());
                String courseName = getCourseName(current.getCourseId());
                change.setCourseName(courseName);
                change.setChangeType("成绩变化");
                change.setChangeDescription(String.format("课程总分从 %s 分变为 %s 分", lastScore, currentScore));
                change.setDetectedTime(new Date());

                changesMapper.insert(change);
            }
        }
    }

    /**
     * 2. 检测排名变化
     */
    private void detectRankingChange(String studentId, CourseProgressEntity current, StudentPerformanceSnapshots last) {
        if (current.getRanking() != null && last.getCourseRanking() != null) {
            Integer currentRank = current.getRanking();
            Integer lastRank = last.getCourseRanking();

            if (!currentRank.equals(lastRank)) {
                PerformanceChanges change = new PerformanceChanges();
                change.setId(UUID.randomUUID().toString());
                change.setStudentId(studentId);
                change.setCourseId(current.getCourseId());
                String courseName = getCourseName(current.getCourseId());
                change.setCourseName(courseName);
                change.setChangeType("排名变化");
                change.setChangeDescription(String.format("课程排名从第 %d 名变为第 %d 名", lastRank, currentRank));
                change.setDetectedTime(new Date());

                changesMapper.insert(change);
            }
        }
    }

    /**
     * 3. 检测进度变化
     */
    private void detectProgressChange(String studentId, CourseProgressEntity current, StudentPerformanceSnapshots last) {
        int currentCompleted = current.getCompletedTasks() != null ? current.getCompletedTasks() : 0;
        int lastCompleted = last.getCompletedTasks() != null ? last.getCompletedTasks() : 0;

        if (currentCompleted != lastCompleted) {
            PerformanceChanges change = new PerformanceChanges();
            change.setId(UUID.randomUUID().toString());
            change.setStudentId(studentId);
            change.setCourseId(current.getCourseId());
            String courseName = getCourseName(current.getCourseId());
            change.setCourseName(courseName);
            change.setChangeType("进度变化");
            change.setChangeDescription(String.format("完成任务数从 %d 个变为 %d 个", lastCompleted, currentCompleted));
            change.setDetectedTime(new Date());

            changesMapper.insert(change);
        }
    }

    /**
     * 4. 检测新任务变化
     */
    private void detectNewAssignments(String studentId, String courseId, LocalDate sinceDate) {
        List<AssignmentStudentEntity> newAssignments = dataAggregationMapper
                .selectNewAssignmentsSince(studentId, courseId, sinceDate.atStartOfDay());

        for (AssignmentStudentEntity assignment : newAssignments) {
            String assignmentName = getAssignmentName(assignment.getAssignmentId());

            PerformanceChanges change = new PerformanceChanges();
            change.setId(UUID.randomUUID().toString());
            change.setStudentId(studentId);
            change.setCourseId(courseId);
            change.setCourseName(getCourseName(courseId));
            change.setAssignmentId(assignment.getAssignmentId());
            change.setAssignmentName(assignmentName);
            change.setChangeType("新任务分配");
            change.setChangeDescription("分配了新任务: " + assignmentName);
            change.setDetectedTime(new Date());

            changesMapper.insert(change);
        }
    }

    /**
     * 5. 检测贡献度变化
     */
    private void detectContributionChanges(String studentId, String courseId,
                                           StudentPerformanceSnapshots lastSnapshot, LocalDate sinceDate) {
        // 获取新提交的贡献度记录
        List<SubmissionEntity> newSubmissions = dataAggregationMapper
                .selectStudentNewSubmissionsSince(studentId, courseId, sinceDate.atStartOfDay());

        for (SubmissionEntity submission : newSubmissions) {
            if (submission.getContributionRate() != null && !submission.getContributionRate().isEmpty()) {
                // 从JSON数组中提取当前学生的贡献率
                BigDecimal studentContributionRate = null;
                for (SubmissionEntity.ContributionItem item : submission.getContributionRate()) {
                    if (item.getStudentId().equals(studentId)) {
                        studentContributionRate = item.getRate();
                        break;
                    }
                }
                
                if (studentContributionRate != null) {
                    String assignmentName = getAssignmentName(submission.getAssignmentId());

                    PerformanceChanges change = new PerformanceChanges();
                    change.setId(UUID.randomUUID().toString());
                    change.setStudentId(studentId);
                    change.setCourseId(courseId);
                    change.setCourseName(getCourseName(courseId));
                    change.setAssignmentId(submission.getAssignmentId());
                    change.setAssignmentName(assignmentName);
                    change.setChangeType("贡献度记录");
                    change.setChangeDescription(String.format("任务 %s 贡献度: %.2f%%",
                            assignmentName, studentContributionRate));
                    change.setDetectedTime(new Date());

                    changesMapper.insert(change);
                }
            }
        }

        // 检测贡献度数值变化（对比历史记录）
        detectContributionValueChanges(studentId, courseId, lastSnapshot);
    }

    /**
     * 检测贡献度数值变化
     */
    private void detectContributionValueChanges(String studentId, String courseId, StudentPerformanceSnapshots lastSnapshot) {
        // 获取当前贡献度记录
        List<Map<String, Object>> currentContributions = parseContributions(getRecentContributions(studentId, courseId));
        List<Map<String, Object>> lastContributions = parseContributions(lastSnapshot.getRecentContributions());

        // 对比找出数值变化的贡献度
        for (Map<String, Object> current : currentContributions) {
            String assignmentId = (String) current.get("assignmentId");
            BigDecimal currentRate = (BigDecimal) current.get("rate");

            // 查找上周的对应记录
            Map<String, Object> lastRecord = findContributionByAssignment(lastContributions, assignmentId);

            if (lastRecord != null) {
                BigDecimal lastRate = (BigDecimal) lastRecord.get("rate");
                if (currentRate != null && lastRate != null && currentRate.compareTo(lastRate) != 0) {
                    String assignmentName = (String) current.get("assignmentName");

                    PerformanceChanges change = new PerformanceChanges();
                    change.setId(UUID.randomUUID().toString());
                    change.setStudentId(studentId);
                    change.setCourseId(courseId);
                    change.setCourseName(getCourseName(courseId));
                    change.setAssignmentId(assignmentId);
                    change.setAssignmentName(assignmentName);
                    change.setChangeType("贡献度变化");
                    change.setChangeDescription(String.format("任务 %s 贡献度从 %s%% 变为 %s%%",
                            assignmentName, lastRate, currentRate));
                    change.setDetectedTime(new Date());

                    changesMapper.insert(change);
                }
            }
        }
    }

    /**
     * 获取近期贡献度记录
     */
    private String getRecentContributions(String studentId, String courseId) {
        List<ContributionRecord> contributions = dataAggregationMapper.selectContributionRecords(studentId, courseId);

        List<Map<String, Object>> records = contributions.stream()
                .map(record -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("assignmentId", record.getAssignmentId());
                    data.put("assignmentName", getAssignmentName(record.getAssignmentId()));
                    data.put("rate", record.getContributionRate());
                    data.put("submissionTime", record.getSubmissionTime());
                    return data;
                })
                .collect(Collectors.toList());

        return JSON.toJSONString(records);
    }

    /**
     * 获取进行中任务
     */
    private String getActiveAssignments(String studentId, String courseId) {
        List<AssignmentStudentVO> assignments = dataAggregationMapper.selectActiveAssignments(studentId, courseId);

        List<Map<String, Object>> activeAssignments = assignments.stream()
                .map(assignment -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("assignmentId", assignment.getAssignmentId());
                    data.put("assignmentName", assignment.getAssignmentName());
                    data.put("status", assignment.getStatus());
                    data.put("assignedTime", assignment.getAssignedTime());
                    return data;
                })
                .collect(Collectors.toList());

        return JSON.toJSONString(activeAssignments);
    }

    /**
     * 解析贡献度JSON
     */
    private List<Map<String, Object>> parseContributions(String contributionsJson) {
        if (StringUtils.isBlank(contributionsJson) || "null".equals(contributionsJson)) {
            return new ArrayList<>();
        }
        try {
            return JSON.parseObject(contributionsJson,
                    new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    /**
     * 按任务ID查找贡献度记录
     */
    private Map<String, Object> findContributionByAssignment(List<Map<String, Object>> contributions, String assignmentId) {
        if (contributions == null) return null;
        return contributions.stream()
                .filter(contrib -> assignmentId.equals(contrib.get("assignmentId")))
                .findFirst()
                .orElse(null);
    }

    private String getAssignmentName(String assignmentId) {
        try {
            return dataAggregationMapper.selectAssignmentNameById(assignmentId);
        } catch (Exception e) {
            return "未知任务";
        }
    }

    private String getCourseName(String courseId) {
        try {
            return dataAggregationMapper.selectCourseNameById(courseId);
        } catch (Exception e) {
            return "未知课程";
        }
    }

    private List<String> getTrackedStudentIds() {
        return studentPerformanceTrackingServiceMapper.selectAllActiveStudentIds();
    }

}
